package com.example.forum.service.impl;

import com.example.forum.dao.CommentDao;
import com.example.forum.dao.DiscussPostDao;
import com.example.forum.domain.Comment;
import com.example.forum.domain.DiscussPost;
import com.example.forum.service.CommentService;
import com.example.forum.utils.HostHolder;
import com.example.forum.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private DiscussPostDao discussPostDao;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public List<Comment> findByEntityType(int entityType, int entityId, int start, int size) {
        return commentDao.findByEntityType(entityType,entityId,start,size);
    }

    @Override
    public Integer findByEntityTypeCount(int entityType, int entityId) {
        return commentDao.findByEntityTypeCount(entityType,entityId);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public void addComment(Comment comment) throws Exception {
        if(comment==null){
            throw new Exception("参数不能为空");
        }
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        comment.setUserId(hostHolder.getUser().getId());
        //添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        commentDao.addComment(comment);
        //修改帖子评论数量
        if(comment.getEntityType()==1){ //该评论是给帖子的评论
            DiscussPost discussPost = discussPostDao.findById(comment.getEntityId());
            discussPostDao.updateCommentCount(comment.getEntityId(),discussPost.getCommentCount()+1);
        }
    }
}
